import {
  config
} from './config.js'

class Http{
  constructor() { 
  }

  sendRequest(url, params,success) {   //同步封装
    var that = this;
    var ts_url = config.ts_url;
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中',
    })
    let token = wx.getStorageSync('token');
    return new Promise(function (resolve, reject) {
      wx.request({
        url: ts_url+url,
        data: params,
        method: "POST",
        header: {
          "Content-Type": "application/json",
          'token': token,//根据自己的接口写header的传参
        },
        success: function (res) {
          resolve(res.data);
          // success(res.data);
          wx.hideNavigationBarLoading()
          wx.hideLoading()
        },
        fail: function (res) {
          reject(res);
        },
      })
    });
  }

  asynRequest(url, param, success){
    var that = this;
    var ts_url = config.ts_url;
    this.sendRequest(url, param).then(function (result) {
      success(result)
    })
  }

  request(url, param, success) {
    var that = this;
    var ts_url = config.ts_url;
    this.sendRequest(url, param).then(function (result) {
      if (result.code == -10010) {
        wx.login({
          success: function (res) {
            if (res.code) {
              let code = res.code;
              wx.showLoading({
                title: '加载中...',
              })
              wx.request({
                url: ts_url + '/index/login/login',
                data: { 'code': code },
                header: {
                  'content-type': 'application/x-www-form-urlencoded',
                },
                method: 'post',//方法也可以改成变量 传入
                success: function (res) {
                  wx.hideLoading()
                  var data = res.data.data;
                  wx.setStorageSync('token', data.token);
                  wx.setStorageSync('userinfo', data.userinfo);
                  that.sendRequest(url, param).then(success);
                }
              })
            }
          }
        })
      } else {
        success(result)
      }
    })
  }
}
export {
  Http
}